package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.message.Article2EsConstants;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmNewsContentDto;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class FreeMarkerServiceImpl implements ArticleFreemarkerService {

    private static final String DETAIL_TMPL_FILE_NAME = "article.ftl";
        @Autowired
        private Configuration configuration;

        @Autowired
        private MinioService minioService;

        @Lazy //延迟注入
        @Autowired
        private ApArticleService apArticleService;

        @Autowired
        private KafkaTemplate<String,String> kafkaTemplate;


    @Override
    @Async("taskExecutor")
    public void buildContentHtml(Long articleId, String content) {

        try {
            Template template = configuration.getTemplate(DETAIL_TMPL_FILE_NAME);
            Map<String, Object> map = new HashMap<>();
            List<WmNewsContentDto> wmNewsContentDtos = WmNewsContentDto.parseContent(content);
            map.put("content",wmNewsContentDtos);
            //调用API生成静态页，存入流中
            StringWriter stringWriter = new StringWriter();
            template.process(map,stringWriter);
            //放入minio
            String fileName = articleId + ".html";
            log.info("文件名：{}",fileName);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes("UTF-8"));
            //        获取到访问路径
            String url = minioService.uploadHtmlFile("", fileName,inputStream );
            log.info("上传后的url=={}",url);
         //   因为是异步执行，为了防止article落库之前，先执行这里的异步操作
        //万一article表的数据还没有commit，这里就无法更新了
            Thread.sleep(2000);
        // 把静态文件的url回填到article中
        ApArticle article = new ApArticle();
        article.setId(articleId);
        article.setStaticUrl(url);
        apArticleService.updateById(article);
            kafkaTemplate.send(Article2EsConstants.ARTICLE_2_ES_TOPIC,""+articleId);
        }catch (Exception e){
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }
}
